package com.liucxu.jiandanl.View.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

import com.liucxu.jiandanl.Business.FreshNewsDetailEvent;
import com.liucxu.jiandanl.Entity.Post;
import com.liucxu.jiandanl.R;
import com.liucxu.jiandanl.Utils.HTMLUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class FreshNewsDetailActivity extends Activity{

    private int id;
    private Post mPost;
    @InjectView(R.id.back)
    ImageView back;
    @InjectView(R.id.detail_webview)
    WebView detail_webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fresh_news_detail);
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        if (intent == null) {
            this.finish();
        } else {
            mPost = (Post) intent.getSerializableExtra("POST");
            id = mPost.getId();
        }
        detail_webview.getSettings().setJavaScriptEnabled(true);
    }

    @Override
    protected void onStop() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        FreshNewsDetailEvent.GetRefreshNewsDetail(id);
    }

    public void onEventMainThread(FreshNewsDetailEvent event) {
        if (event.getResultCode() == 0) {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        } else {
            String htmlContent = HTMLUtils.formatHTMLForFreshNewsDetail(event.freshNewsDetail.getContent(), mPost);
            detail_webview.loadDataWithBaseURL("", htmlContent, "text/html", "utf-8", "");
        }
    }

    @OnClick(R.id.back)
    void doFinish(){
        this.finish();
    }
}
